package com.adinnet.admin.common;

import com.adinnet.common.upload.UploadUtils;
import com.adinnet.core.BaseController;
import com.adinnet.core.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {

    /**
     * 上传单个文件
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadFile")
    public JsonResult uploadOneFile(HttpServletRequest request) {
        MultipartHttpServletRequest mureq = (MultipartHttpServletRequest) request;
        MultipartFile file = mureq.getFile("file");
        String url = UploadUtils.uploadFile(file);
        return ok(url);
    }


    /**
     * 上传富文本文件
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadLayeditFile")
    public JsonResult uploadLayeditFile(HttpServletRequest request) {
        MultipartHttpServletRequest mureq = (MultipartHttpServletRequest) request;
        MultipartFile file = mureq.getFile("file");
        String url = UploadUtils.uploadFile(file);
        HashMap<String, String> r = new HashMap<>();
        r.put("src",url);
        r.put("title","title");
        return JsonResult.ok(0,"上传成功").put("data",r);
    }

    /**
     * 上传多个文件
     *
     * @param files
     * @return
     */
    @PostMapping("/uploadManyFile")
    public JsonResult uploadManyFile(@RequestParam(value = "files", required = false) MultipartFile[] files) {
        if (null == files && files.length == 0) {
            return error("文件必传");
        }
        StringBuffer sb = new StringBuffer();
        for (MultipartFile multipartFile : files) {
            String path = UploadUtils.uploadFile(multipartFile);
            if (sb.toString().isEmpty()) {
                sb.append(path);
            } else {
                sb.append(",").append(path);
            }
        }
        return ok(sb.toString());
    }

    /**
     * 删除多个文件
     *
     * @param fileName
     * @return
     */
    @PostMapping("/delManyFile")
    public JsonResult batchDeleteFile(List<String> fileName) {
        if (UploadUtils.batchDeleteFile(fileName)) {
            return ok("删除成功");
        } else {
            return error("删除失败");
        }
    }
}
